package com.runvp.rest.auth;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.constant.ConstantKey;
import com.runvp.common.constant.ConstantRedisKey;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.util.code.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/app/auth")
public class KaptchaController {

    @Autowired
    private RedisCache redisService;


    /**
     * 获取验证码
     */
    @GetMapping("/kaptcha/{phone}")
    public AjaxResult kaptcha(@PathVariable("phone") String phone) throws Exception {
        try {
            // 生产验证码字符串并保存到session中
            String createText = VerifyCodeUtils.generateVerifyCode(4);
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            redisService.setCacheObject(ConstantRedisKey.RANDOM_CODE_PREFIX + phone, createText, ConstantKey.RANDOM_CODE_EXPIRE, TimeUnit.SECONDS);
            String baseStr = VerifyCodeUtils.getBase64Img(createText);
            return AjaxResult.success(JSONObject.toJSON("data:image/jpg;base64," + baseStr));
        } catch (Exception e) {
            return AjaxResult.error("请重新获取验证码");
        }
    }

}
